﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using yt = Google.YouTube;

// TODO: Tier this bitch out and make a proper BLL

/// <summary>Code that is common to, or used by, multiple pages</summary>
namespace Common
{
	public static class Search
	{

		/// <summary>Create and returns and Google.GData.Client.AtomFee from url with the specific start and number of items  </summary>  
		/// <param name="url">URL</param>  
		/// <param name="start">Start index</param> 
		/// <param name="number">Number of hits to retrieve</param>
		/// <returns>AtomFeed for displaying</returns>  
		public static AtomFeed GetFeed(string url, int start, int number)
		{
			FeedQuery fquery = new FeedQuery("")
			{
				Uri = new Uri(url),
				StartIndex = start,
				NumberToRetrieve = number
			};
			Service service = new Service("youtube", "CowHut");
			return service.Query(fquery);
		}
		/// <summary>Create and returns and Google.GData.Client.AtomFee from url with the specific start and number of items  </summary>  
		/// <param name="url">URL</param>  
		/// <param name="start">Start index</param> 
		/// <param name="number">Number of hits to retrieve</param>
		/// <param name="query">Search query</param>
		/// <returns>AtomFeed for displaying</returns>  
		public static AtomFeed GetFeed(string url, int start, int number, string query)
		{
			FeedQuery fquery = new FeedQuery()
			{
				Uri = new Uri(url),
				StartIndex = start,
				NumberToRetrieve = number,
				Query = query
			};
			Service service = new Service("youtube", "CowHut");
			return service.Query(fquery);
		}
		/// <summary>Create and returns Google.GData.Client.AtomFeed from url.  Returns ALL items, up to 10,000.</summary>  
		/// <param name="url">URL</param>  
		/// <param name="query">Query to execute</param>
		/// <returns>AtomFeed for displaying</returns>  
		public static AtomFeed GetFeed(FeedQuery query, int max = 10000)
		{
			Service service = new Service("youtube", "CowHut");
			AtomFeed 
				feed = service.Query(query), 
				temp = feed;

			for (int i = 1; temp.Entries.Count > 0 && i * 25 < max; i++)
			{
				try { temp = service.Query(new FeedQuery(query.Uri + "&start-index=" + (25 * i).ToString())); }
				catch { 
					// Execution of request failed: http://gdata.youtube.com/feeds/videos?q=lockergnome&author=lockergnome&start-index=1000
					//								http://gdata.youtube.com/feeds/videos?q=lockergnome&author=lockergnome&max-results=25&key=AI39si7B-X6pG5-1i2luWo5mzPkUsjYlzXD573ZPvI03nKSbTBPFxggUDHSz7fPpfADGjxjkccWF-kdZXIt9Irh-GcWpqQOVxg&max-results=25
					return feed; }
				foreach (AtomEntry entry in temp.Entries)
					try {
						feed.Entries.Add(entry); }
						catch { }
			}


			return feed;
		}

	}
}